import util from '@/utils/util'
import 'echarts/lib/component/visualMap'
import store from '@/store'
import { getEquipStatusLabel } from "./equipStatus";
const device = store.state.app.device
const rateFormatter = (name,data) => {
  var total = 0;
  var tarValue;
  for (var i = 0; i < data.length; i++) {
    total += data[i].value;
    if (name === data[i].name) {
      tarValue = data[i].value;
    }
  }
  var p = total && tarValue > 0 ? ((tarValue / total) * 100).toFixed(2)+'%' : 0;
  return name + "("+ tarValue + "，" + p + ")";
}

const isExistArray = (value, index, ar) =>{
  if (value?.length) {
    return true;
  }
  else {
    return false;
  }
}
export const getAbnomalOption = function (data,abnormalTotal,rateComplete) {
  return {
    backgroundColor: "transparent",
    title: {
      text: `异常数:${abnormalTotal}`,
      subtext: `完成率:${rateComplete}`,
      left: 0,
      top:"center",
      textStyle:{
        fontSize: 12
      },
      subtextStyle:{
        fontSize: 12,
        color:'#303133',
        fontWeight:"bold"
      },
    },
    tooltip: {
      show: true,
      triggerOn:device == "desktop" ? "mousemove" : "click",
      formatter: "{b}: {c} ({d}%)",
      confine: false,
      appendToBody: false,
    },

    grid: {
      top: 'center',
      left: 'left'
    },

    graphic: [{
      type: "text",
      left: 20,
      top:"center",
      style: {
        // text:`异常数${abnormalTotal}`
      }
    }],

    legend: {
      selectedMode:true,
      show: true,
      orient: "vertical",
      right:0,
      top:"center",
      textStyle:{
        fontSize: 10,
        color:'#303133'
      },
      formatter:(name) => {
        return rateFormatter(name,data)
      }
    },

    series: [{
      type: "pie",
      radius: '58%',
      right: '12%',
      avoidLabelOverlap: false,    //禁止标签重叠
      label: {
        show: false,
        // position: "outside",
        // color: '#313131',
        // formatter: "{b}\n{c} ({d}%)",
        // alignTo: 'edge',
        // minMargin: 10,
        // edgeDistance: 10,
        // lineHeight: 10,
        // fontSize: 8,
        // rich: {
        //   num: {
        //     fontSize: 10,
        //     color: '#999',
        //     lineHeight: 10
        //   }
        // }
      },
      labelLine: {
        show: false,
      },
      itemStyle: {
        // color: (params) => {
        //   const {
        //     dataIndex
        //   } = params
        //   const color = INSPECTION_COLOR[dataIndex]
        //   return {
        //     type: 'linear',
        //     x: 0,
        //     y: 1,
        //     x2: 0,
        //     y2: 0,
        //     colorStops: [{
        //       offset: 0,
        //       color: "#00E898"// 0% 处的颜色
        //     }, {
        //       offset: 1,
        //       color: "#00E898" // 100% 处的颜色
        //     }],
        //     global: false
        //   }
        // }
        color: function (colors) {
         var colorList = [ "#5470c6","#5cc3eb","#fac858","#91cc75","#ab9578"];
         return colorList[colors.dataIndex];
        }
      },
      data: data
    }]
  }
}

export const getWarnOption = function (data,warnTotal) {
  return {
    backgroundColor: "transparent",
    title: {
      text: `预警数:${warnTotal}`,
      left: 0,
      top:"center",
      textStyle:{
        fontSize: 12
      },
    },
    tooltip: {
      show: true,
      formatter: "{b}: {c} ({d}%)",
      triggerOn:device == "desktop" ? "mousemove" : "click",
      confine: false,
      appendToBody: false,
    },

    grid: {
     top: 'center',
     right: 'right'
    },

    graphic: [{
      type: "group",
      left: "center",
      right: "center",
      top: "center"
    }],

    legend: {
      selectedMode:true,//取消图例上的点击事件
      orient: "vertical",
      show: true,
      right:0,
      top:"center",
      textStyle:{
        fontSize: 10,
        color:'#303133',
      },
      formatter:(name) => {
        return rateFormatter(name,data)
      }
    },

    series: [{
      type: "pie",
      radius: '58%',
      right: '10%',
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: "outside",
        color: '#313131',
        formatter: "{b}\n{c} ({d}%)",
        // alignTo: 'edge',
        // formatter: '{b}\n{c}',
        // minMargin: 5,
        // edgeDistance: 10,
        // lineHeight: 15,
        // rich: {
        //   num: {
        //     fontSize: 13,
        //     color: '#999',
        //     lineHeight: 20
        //   }
        // }
      },
      labelLine: {
        show: false,
      },

      itemStyle: {
        // color: (params) => {
        //   const {
        //     dataIndex
        //   } = params
        //   const color = INSPECTION_COLOR[dataIndex]
        //   return {
        //     type: 'linear',
        //     x: 0,
        //     y: 1,
        //     x2: 0,
        //     y2: 0,
        //     colorStops: [{
        //       offset: 0,
        //       color: "#00E898"// 0% 处的颜色
        //     }, {
        //       offset: 1,
        //       color: "#00E898" // 100% 处的颜色
        //     }],
        //     global: false
        //   }
        // }
        color: function (colors) {
         var colorList = [ "#FF9300","#ab9578"];
         return colorList[colors.dataIndex];
        }
      },
      data: data
    }]
  }
}


const INSPECTION_COLOR = [
  ['#00CC5E', '#00E898'],
  ['#00CC5E', '#00E898'],
  ['#8297F8', '#9BC3FC'],
]
export const getTaskOption = function (data,taskTotal,rateComplete) {
  return {
    backgroundColor: "transparent",
    title: {
      text: `任务数:${taskTotal}`,
      subtext: `完成率:${rateComplete}`,
      left: 0,
      top:"center",
      textStyle:{
        fontSize: 12
      },
      subtextStyle:{
        fontSize: 12,
        color:'#303133',
        fontWeight:"bold"
      },
    },
    tooltip: {
      show: true,
      formatter: "{b}: {c} ({d}%)",
      triggerOn:device == "desktop" ? "mousemove" : "click",
      confine: false,
      appendToBody: false,
    },
    grid: {
      top: "center",
      left:  "center"
    },
    graphic: [{
      type: "group",
      left: "center",
      right: "center",
      top: "center"
    }],
    legend: {
      selectedMode:true,
      show: true,
      orient: "vertical",
      top: "center",
      right:0,
      textStyle:{
        fontSize: 10,
        color:'#303133'
      },
      formatter:(name) => {
        return rateFormatter(name,data)
      }
    },
    series: [{
      type: "pie",
      radius: '70%',
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: "outside",
        color: '#313131',
        formatter: "{b}\n{c} ({d}%)",
        // show: true,
        // position: "outside",
        // fontSize: util.pxToFixPx(14, 'number', 12),
        // color: '#313131',
        // formatter: "{b}\n{c} ({d}%)",
        // alignTo: 'edge',
        // formatter: '{b}\n{c}',
        // minMargin: 5,
        // edgeDistance: 10,
        // lineHeight: 15,
        // rich: {
        //   num: {
        //     fontSize: 13,
        //     color: '#999',
        //     lineHeight: 20
        //   }
        // }
      },
      labelLine: {
        show: false,
      },
      itemStyle: {
        color: function (colors) {
          var colorList = [
           "#5470c6","#5cc3eb","#9e56be","#fac858","#ee6666","#91cc75","#ab9578"
          ];
          return colorList[colors.dataIndex];
        }
      },
      data: data
    }]
  }
}

export const getMonitorOption = function (dataX,dataY,warnMin,warnMax,abnormalMin,abnormalMax,indexValueUnit) {
  const MaxValueLen = Math.max(...dataY).toString().length;
  const option = {
    //鼠标悬浮提示
    tooltip: {
      show: true,
      formatter: function(param) {
        return `${param[0].axisValue.slice(0, -3)}：${param[0].value}${indexValueUnit && indexValueUnit != '无' ? indexValueUnit : ""}`
      },
      position: "right",
      confine: false,
      trigger: 'axis',
      appendToBody: false
    },

    grid: {
      left: dataY?.length ? (MaxValueLen + Math.floor(MaxValueLen / 3)) * 9 + 30 : 70,
      right: 50,
      top:20,
      bottom:20
    },

    xAxis: {
      type: 'category',
      data: dataX,
      splitLine: {
        //网格线
        show: false
      },
      // x轴标题信息
      nameTextStyle: {
        color: '#000', //  字体颜色
        fontSize: 12, //  字体大小
        fontWeight: 'nomal'
      },
      axisTick: {
        show: false, //是否展示刻度线
        inside: true //刻度线朝内还是朝外
      },
      axisLine: {
        //坐标轴轴线相关设置
        show: 'true', //是否显示坐标轴轴线
        lineStyle: {
          color: '#C8D0D7', //坐标轴线线的颜色
          width: '1' //坐标轴线线宽
        }
      },
      axisLabel:{
        rotate:0,
        formatter(value) {
          return value.slice(0,-3);
        }
      }
    },

    yAxis: {
      nameTextStyle: {
        //  单位样式
        color: '#7D8292', //  字体颜色
        fontWeight: 'nomal',
        fontSize: 12 //  字体大小
      },
      axisLine: {
        show: false, //是否显示y轴
        lineStyle: {
          color: '#7D8292', //坐标轴线线的颜色
          width: '1' //坐标轴线线宽
        }
      },
      axisTick: {
        //是否展示刻度线
        show: false,
        inside: true //刻度线朝内还是朝外
      },
      axisLabel: {
        //默认展示最后一个点
        fontSize: '12', //文字的字体大小
        fontWeight: 'nomal',//加粗
        showMaxLabel: true          //是否显示最大刻度
      },
      splitLine: {
        //网格线
        show: true,
        lineStyle: {
          color: ["#C8D0D7"],
          type: "dotted",
        },
      },
      type: 'value',
      min:0,
      max:0,
      // interval:1
    },
    visualMap: [],
    series: [],
  }
  option.yAxis.min = 0;
  option.yAxis.max = 0;
  option.visualMap = [];
  option.series = [];
  option.series[0] = {
    lineStyle: {
      width: 4
    },
    itemStyle: {
      color: (params) => {
        return {
          type: 'linear',
          x: 0,
          y: 1,
          x2: 0,
          y2: 0,
          colorStops: [{
            offset: 0,
            color: "#00CC5E" // 0% 处的颜色
          }, {
            offset: 1,
            color: "#00E898" // 100% 处的颜色
          }],
          global: true
        }
      }
    },
    data: dataY,
    type: 'line',
    symbolSize:8,
    symbol:'circle',
    smooth: false
  }
  if(!(warnMax.some(isExistArray)) && !(warnMin.some(isExistArray)) && !(abnormalMax.some(isExistArray)) && !(abnormalMin.some(isExistArray))){//没有预警区间,异常区间
    option.series[0].lineStyle.color = {//给折线设置固定颜色
      type: 'linear',
      x: 0,
      y: 1,
      x2: 0,
      y2: 0,
      colorStops: [
        {offset: 0,color: "#00CC5E" },// 0% 处的颜色
        {offset: 1,color: "#00E898"} // 100% 处的颜色
      ],
      global: true
    }
    option.yAxis.min = Math.floor(Math.min.apply(null, dataY));
    option.yAxis.max = Math.ceil(Math.max.apply(null, dataY));
    // option.yAxis.interval = ((option.yAxis.max - option.yAxis.min)/6).toFixed(2)
  }
  else{
    let warnMinArr = [];
    let warnMaxArr = [];
    let abnormalMinArr = [];
    let abnormalMaxArr = [];
    if(warnMax.some(isExistArray) || warnMin.some(isExistArray)){//存在预警区间
      let warnArr = warnMax?.length ? warnMax : warnMin;
      delete option.series[0].lineStyle.color;
      if(warnMin?.length){
        warnMin.forEach(ele => {
          if(ele?.length){
            option.series.push({
              data: ele,
              type: 'line',
              lineStyle: {
                width: 3,
                type: "dotted",
                color:"#FF9300"
              }
            })
            warnMinArr.push(ele[0])
          }
        })
      }
      if(warnMax?.length){
        warnMax.forEach(ele => {
          if(ele?.length){
            option.series.push({
              data: ele,
              type: 'line',
              lineStyle: {
                width: 3,
                type: "dotted",
                color:"#FF9300"
              }
            })
            warnMaxArr.push(ele[0])
          }
        })
      }
      if(warnArr?.length){
        warnArr.map((item,index)=>{
          option.visualMap.push({
            type: 'piecewise',
            show: false,
            dimension: 1,
            seriesIndex: 0,
            inRange: { //定义 在选中范围中 的视觉元素
              color: ['#00CC5E', '#00E898']
            },
            pieces: [
              {
                lte:warnMax?.length && warnMax[index]?.length ? warnMax[index][0] : warnMin[index][0] * 10000,
                gte:warnMin?.length && warnMin[index]?.length ? warnMin[index][0] : -warnMax[index][0] * 10000
              }
            ],
            outOfRange: { // 在选中范围外的视觉元素
              color:["#FF9300"]
            }
          })
        })
      }
    }
    if(abnormalMax.some(isExistArray) || abnormalMin.some(isExistArray)){//存在异常区间
      let abnormalArr = abnormalMax?.length ? abnormalMax : abnormalMin;
      delete option.series[0].lineStyle.color;
      if(abnormalMin?.length){
        abnormalMin.forEach(ele => {
          if(ele?.length){
            option.series.push({
              data: ele,
              type: 'line',
              lineStyle: {
                width: 3,
                type: "dotted",
                color:"#f54e1e"
              }
            })
            abnormalMinArr.push(ele[0])
          }
        })
      }
      if(abnormalMax?.length){
        abnormalMax.forEach(ele => {
          if(ele?.length){
            option.series.push({
              data: ele,
              type: 'line',
              lineStyle: {
                width: 3,
                type: "dotted",
                color:"#f54e1e"
              }
            })
            abnormalMaxArr.push(ele[0])
          }
        })
      }
      if(abnormalArr?.length){
        abnormalArr.map((item,index)=>{
          option.visualMap.push({
            type: 'piecewise',
            show: false,
            dimension: 1,
            seriesIndex: 0,
            inRange: { //定义 在选中范围中 的视觉元素
              color: ['#00CC5E', '#00E898']
            },
            pieces: [
              {
                lte:abnormalMax?.length && abnormalMax[index]?.length ? abnormalMax[index][0] : abnormalMin[index][0] * 10000,
                gte:abnormalMin?.length && abnormalMin[index]?.length ? abnormalMin[index][0] : -abnormalMax[index][0] * 10000,
              }
            ],
            outOfRange: { //在选中范围外的视觉颜色
              color:["#f54e1e"]
            }
          })
        })
      }
    }
    //预警区间,异常区间,和Y轴数据拼接，然后比较获取最大最小值作为坐标轴的最大最小值
    let newArr = dataY.concat(warnMinArr,warnMaxArr,abnormalMinArr,abnormalMaxArr);
    option.yAxis.min = Math.floor(Math.min.apply(null, newArr));
    option.yAxis.max = Math.ceil(Math.max.apply(null, newArr));
    // option.yAxis.interval = Number((option.yAxis.max - option.yAxis.min)/6).toFixed(2)
  }
  return option
};

export const getEquipStatusOption = function(dataX, dataY) {
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(param) {
        return param[0].axisValue.slice(0, -3) + "：" + getEquipStatusLabel(param[0].value);
      },
      position: "right",
      confine: false,
      trigger: 'axis',
      appendToBody: false
    },
    grid: {
      left: 70,
      right: 50,
      top:20,
      bottom:20
    },
    xAxis: {
      type: 'category',
      data: dataX,
      splitLine: {
        //网格线
        show: false
      },
      // x轴标题信息
      nameTextStyle: {
        color: '#000', //  字体颜色
        fontSize: 12, //  字体大小
        fontWeight: 'nomal'
      },
      axisTick: {
        show: false, //是否展示刻度线
        inside: true //刻度线朝内还是朝外
      },
      axisLine: {
        //坐标轴轴线相关设置
        show: 'true', //是否显示坐标轴轴线
        onZero: false,
        lineStyle: {
          color: '#C8D0D7', //坐标轴线线的颜色
          width: '1' //坐标轴线线宽
        }
      },
      axisLabel:{
        rotate:0,
        formatter(value) {
          return value.slice(0,-3);
        }
      }
    },
    yAxis: {
      nameTextStyle: {
        //  单位样式
        color: '#7D8292', //  字体颜色
        fontWeight: 'nomal',
        fontSize: 12 //  字体大小
      },
      axisLine: {
        show: false, //是否显示y轴
        lineStyle: {
          color: '#7D8292', //坐标轴线线的颜色
          width: '1' //坐标轴线线宽
        }
      },
      axisTick: {
        //是否展示刻度线
        show: false,
        inside: true //刻度线朝内还是朝外
      },
      axisLabel: {
        //默认展示最后一个点
        fontSize: '12', //文字的字体大小
        fontWeight: 'nomal',//加粗
        showMaxLabel: true,          //是否显示最大刻度
        formatter: function(value, index) {
          return getEquipStatusLabel(value);
        }
      },
      splitLine: {
        //网格线
        show: true,
        lineStyle: {
          color: ["#C8D0D7"],
          type: "dotted",
        },
      },
      type: 'value',
      min: -2,
      max: 1,
      interval:1
    },
    series: {
      data: dataY,
      type: 'line',
      step: true,
      lineStyle: {
        width: 4,
        color: {//给折线设置固定颜色
          type: 'linear',
          x: 0,
          y: 1,
          x2: 0,
          y2: 0,
          colorStops: [
            {offset: 0,color: "#00CC5E" },// 0% 处的颜色
            {offset: 1,color: "#00E898"} // 100% 处的颜色
          ],
          global: true
        }
      },
      itemStyle: {
        color: (params) => {
          return {
            type: 'linear',
            x: 0,
            y: 1,
            x2: 0,
            y2: 0,
            colorStops: [{
              offset: 0,
              color: "#00CC5E" // 0% 处的颜色
            }, {
              offset: 1,
              color: "#00E898" // 100% 处的颜色
            }],
            global: true
          }
        }
      },
      symbolSize:8,
      symbol:'circle',
      smooth: false
    },
    // visualMap: {
    //   show: false,
    //   pieces: [
    //     {
    //       gt: -1.5,
    //       lte: -0.5,
    //       color: 'rgba(153, 153, 153, 0.5)'
    //     },
    //     {
    //       gt: -0.5,
    //       lte: 0.5,
    //       color: '#F54E1E'
    //     },
    //     {
    //       gt: 0.5,
    //       lte: 1.5,
    //       color: '#34855C'
    //     },
    //   ],
    //   outOfRange: {
    //     color: '#999999'
    //   }
    // }
  };
  return option
}
